package com.andy.basics;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class FormatterFactory {

	private Map<String, Formatter> formatters;

	public FormatterFactory() {
		this.formatters = new HashMap<String, FormatterFactory.Formatter>();
		this.formatters.put("dateFormatter", new DateFormatter());
		this.formatters.put("ageFormatter", new AgeFormatter());
		this.formatters.put("genderFormatter", new GenderFormatter());

	}

	public String format(String formatter, Object value, String pattern) {
		if ((formatter == null) || (pattern == null)) {
			return (String) value;
		}
		if (value == null) {
			return "N/A";
		}
		Formatter f = this.formatters.get(formatter);
		if (f == null) {
			return "" + value;
		}
		return f.format(value, pattern);
	}

	interface Formatter {
		public String format(Object data, String pattern);
	}

	class DateFormatter implements Formatter {
		private Map<String, SimpleDateFormat> formatters = new HashMap<String, SimpleDateFormat>();

		public String format(Object data, String pattern) {
			SimpleDateFormat sdf = this.formatters.get(pattern);
			if (sdf == null) {
				sdf = new SimpleDateFormat(pattern);
				this.formatters.put(pattern, sdf);
			}

			return sdf.format((Date) data);
		}
	}

	class AgeFormatter implements Formatter {

		public String format(Object data, String pattern) {

			Calendar cal1 = Calendar.getInstance(TimeZone.getDefault());
			Calendar cal2 = Calendar.getInstance(TimeZone.getDefault());
			cal2.setTime((Date) data);

			return (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) + " " + pattern;
		}
	}

	class GenderFormatter implements Formatter {
		public String format(Object data, String pattern) {
			return "M".equalsIgnoreCase("" + data) ? "Male" : "Female";
		}
	}
}
